"""
东鹏特饮签到

支持多用户运行

入口：微信小程序----东鹏特饮

多用户用&隔开
例如：openid1&openid2

cron: 55 9 * * *
const $ = new Env("东鹏特饮签到");
"""
import requests
import re
import os
import time
import json
from datetime import datetime
import cloudscraper
import io
import logging
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from notify import send

# 创建 StringIO 对象
log_stream = io.StringIO()

# 配置 logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# 创建控制台 Handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(
    logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

# 创建 StringIO Handler
stream_handler = logging.StreamHandler(log_stream)
# stream_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

# 将两个 Handler 添加到 logger
logger.addHandler(console_handler)
logger.addHandler(stream_handler)

#分割变量
if 'dpopenid' in os.environ:
    dpopenid = re.split("&",os.environ.get("dpopenid"))
    logger.info(f"查找到{len(dpopenid)}个账号")
else:
    dpopenid =['']
    print('dpopenid')


def getToken(openid):
    
    # 创建一个 cloudscraper 实例（它会自动处理 cookies 和 challenge）
    scraper = cloudscraper.create_scraper()

    # 登录的目标 URL
    url = f'https://consume-gw.xdp8.cn/member/applet/authToken?openid={openid}'

    # 请求头（可选，但更真实）
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c33)XWEB/13839"
    }
    
    # 发送 POST 请求（绕过 Cloudflare）
    response = scraper.get(url, headers=headers)
    if response.status_code == 200:
        data = response.json()
        logger.info((f"登录成功，正在获取token"))
        token = data["data"]["token"]
    return token


def qd(token):
    # 创建一个 cloudscraper 实例（它会自动处理 cookies 和 challenge）
    
    scraper = cloudscraper.create_scraper()
    
    # 登录的目标 URL
    url = 'https://consume-gw.xdp8.cn/integral/applet/integral/xcxSignIn'

    # 请求头（可选，但更真实）
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0",
        "token": token
    }
    
    # 发送 GET 请求（绕过 Cloudflare）
    response = scraper.get(url, headers=headers)
    if response.status_code == 200:
        data = response.json()
        if data["status"] == "Success":
            dp_coin = data["data"]
            logger.info((f"签到成功，获得{qd_coin}能量"))
        else:
            logger.info((f"{data['message']}"))
    return data

def get_coin(token):
    # 创建一个 cloudscraper 实例（它会自动处理 cookies 和 challenge）
    
    scraper = cloudscraper.create_scraper()
    
    # 登录的目标 URL
    url = 'https://consume-gw.xdp8.cn/integral/applet/integral/xcxFindIntegral'

    # 请求头（可选，但更真实）
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0",
        "token": token
    }
    
    # 发送 GET 请求（绕过 Cloudflare）
    response = scraper.get(url, headers=headers)
    if response.status_code == 200:
        data = response.json()
        if data["status"] == "Success":
            coin = data["data"]["integral"]
            logger.info((f"当前有{coin}能量"))
        else:
            logger.info((f"{data['message']}"))
    return coin

def main():
    z = 1
    for openid in dpopenid:
        try:
            logger.info(f'登录第{z}个账号')
            logger.info('----------------------')
            token = getToken(openid)
            qd(token)
            get_coin(token)
            logger.info('----------------------')
            z = z + 1
        except Exception as e:
            logger.info('未知错误')

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        logger.info('未知错误')
    try:
        log_contents = log_stream.getvalue()
        send("东鹏特饮：", log_contents)
    except Exception as e:
        logger.info('小错误')